import { Global, Module } from '@nestjs/common';
import configuration from './config';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { UserModule } from './module/system/user/user.module';
import { MenuModule } from './module/system/menu/menu.module';
import { RoleModule } from './module/system/role/role.module';
import { BaseEntitySubscriber } from 'src/common/subscriber/BaseEntitySubscriber';
import { AuthModule } from './module/auth/auth.module';
import { APP_GUARD } from '@nestjs/core';
import { JwtAuthGuard } from 'src/common/guards/jwt-auth.guard';
import { DictModule } from './module/system/dict/dict.module';

@Global()
@Module({
  imports: [
    ConfigModule.forRoot({
      cache: true,
      isGlobal: true,
      load: [configuration],
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        return {
          type: 'mysql',
          entities: [__dirname + '/**/*.entity{.ts,.js}'], // 读取实体文件
          ...configService.get('db.mysql'), // 读取配置
          autoLoadEntities: true, // 自动加载实体
          subscribers: [BaseEntitySubscriber], // 注册订阅者
        } as TypeOrmModuleOptions;
      },
    }),
    UserModule,
    MenuModule,
    RoleModule,
    AuthModule,
    DictModule,
  ],
  controllers: [],

  providers: [
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard, // 全局启用身份验证
    },
  ],
})
export class AppModule {}
